package com.lans.search;

/**
 * @author: lans
 * @date: 2025/3/9
 * @name: 刘宇
 */
public class BinarySearch {
    public static void main(String[] args) {
        //二分查找算法的前提是一个有序的序列
        int[] arr = {10,21,32,42,543,6575,4354546};
        int search = search(arr,0,arr.length-1,543);
        System.out.println("search = " + search);
    }

    //二分查找
    public static int search(int[] arr,int left,int right,int target) {
        if(left>right){
            return -1;
        }
        //求出中间索引值
        int mid = (left+right)/2;
        //求出中间索引值对应的元素
        int midVal = arr[mid];
        if(target>midVal){
            return search(arr,mid+1,right,target);
        }else if(target<midVal){
            return search(arr,left,mid-1,target);
        }else{
            return mid;
        }
    }
}